package com.cm.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cm.common.utils.COSStorage;
import com.cm.common.utils.StringUtil;
import com.cm.common.entity.User;
import com.cm.user.entity.dto.UserKeyWordDTO;
import com.cm.user.mapper.UserMapper;
import com.cm.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @类 名：UserServiceImpl </br>
 * @描 述：</br>
 * @日 期：2020/9/23 17:41</br>
 * @作 者：刘海龙</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean login(String account, String password) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        queryWrapper.eq("password", password);
        List<User> users= userMapper.selectList(queryWrapper);
        if (users.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean insert(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account",user.getAccount());
        List<User> users= userMapper.selectList(queryWrapper);
        if(users.size() > 0){
            return false;
        }
        userMapper.insert(user);
        return true;
    }

    @Override
    public boolean delete(Long id) {
        String url=userMapper.selectById(id).getPhoto();
        String key= StringUtil.getKey(url);
        if(userMapper.deleteById(id)<0){
            return false;
        }
        COSStorage.delete(key);
        return true;
    }

    @Override
    public User select(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean update(User user) {
        Long id =user.getId();
        String url=userMapper.selectById(id).getPhoto();
        if(url!=user.getPhoto()){
            String key= StringUtil.getKey(url);
            COSStorage.delete(key);
        }
        if(userMapper.updateById(user)>0){
            return true;
        }
        return false;
    }
    @Override
    public IPage<User> getUserList(UserKeyWordDTO userKeyWordDTO) {
        // 分页
        Page<User> page = new Page<>();
        userKeyWordDTO.setCurrentPage((userKeyWordDTO.getCurrentPage()-1)*userKeyWordDTO.getPageSize());
        List<User> userList=userMapper.getUserList(userKeyWordDTO);
        page.setRecords(userList);
        page.setCurrent(userKeyWordDTO.getCurrentPage());
        page.setSize(userKeyWordDTO.getPageSize());
        int count=userMapper.getUserTotal(userKeyWordDTO);
        page.setTotal(count);
        return page;
    }
}
